<?php
/**
 * Demo Websocket Lesson 2 - SERVER CODE
 * -----------------------------------------
 * @Topic  : Online ChatRoom
 * @Author : ANHVNSE02067 <anhvnse@gmail.com>
 * @Website: www.nhatanh.net
 */

require_once "./Websockets.php";
require_once "./Message.php";

class Server extends WebSocketServer
{
    private $_serverMessage;

    public function __construct($addr, $port)
    {
        parent::__construct($addr, $port);
        $this->_serverMessage = new Message('!', 'red', '');
    }

    // @override
    protected function connected($user)
    {
        // Send welcome message to user
        $this->_serverMessage->message = 'Welcome to Chatroom!';
        $this->send($user, $this->_serverMessage->serialize());
    }    
	public $numbers=0;
    // @override
    protected function process($user, $message)
    {
		// 接收到用户发送来的数据
        $Message = new Message();

		// 发送回去的数据接口
        $this->sendAll(  $Message->unserialize($message)     );
    }

    // @override
    protected function closed($user)
    {
        // Alert on server
        echo "User $user->id  closed connection".PHP_EOL;
    }

    /**
     * Send Message to ALl Users
     */
    protected function sendAll(Message $message)
    {
        if (!empty($this->users)) {
			
			// 分发给所用当前的$user

            foreach ($this->users as $user) {
				echo ':::'.$this->numbers ++ ;
                $this->send($user, $message->serialize());
            }
        }
    }

    public function __destruct()
    {
        echo "Server destroyed!".PHP_EOL;
    }
}


$addr = '192.168.67.128';
$port = '9000';

$server = new Server($addr, $port);
$server->run();
